package com.example.todolist.common;

import com.example.todolist.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: yoonada
 * @email: m15602498163@163.com
 * @create: 2021-09-06 21:00
 * @description: 全局异常处理类
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public BaseResponse exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("接口:{}发生异常,异常摘要:{}", request.getRequestURI(), e.getMessage(), e);
        return BaseResponse.isFailed(e.getMessage());
    }

    /**
     * 自定义Validated参数校验异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public BaseResponse handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        StringBuilder errorInfo = new StringBuilder();
        BindingResult bindingResult = e.getBindingResult();
        for (int i = 0; i < bindingResult.getFieldErrors().size(); i++) {
            if (i > 0) {
                errorInfo.append(",");
            }
            FieldError fieldError = bindingResult.getFieldErrors().get(i);
            errorInfo.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage());
        }
        String errorInfos = errorInfo.toString();
        log.error("接口:{}发生参数校验异常,异常摘要:{}", request.getRequestURI(), errorInfos);
        return BaseResponse.isFailed(errorInfos);
    }

}